<?php

namespace app\admin\controller\workteam;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use think\Db;

/**
 * 日志
 * @internal
 */
class Log extends Backend
{

    protected $model = null;
    protected $taskfeild = [];
    protected $projectfeild = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new  \app\admin\model\workteam\Log();
    }

    /**
     * 查看
     */
    public function index($project_id=null,$task_id=null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $filter_w=[];
        $task_id?$filter_w['task_id'] = $task_id:'';
        $project_id?$filter_w['project_id'] = $project_id:'';
        if (!$filter_w){
            //TODO 不存在就返回 ，未做权限范围判断
            $result = array("total" =>0, "rows" =>[]);
            return json($result);
        }
        //判断权限
        $auth = new \addons\workteam\library\Auth();
        if ($task_id&&!$auth->taskAuth($task_id, $this->auth)) {
            $this->error(__('您没有权限查看'));
        }
        if ($project_id&&!$auth->projectAuth($project_id, $this->auth)){
            $this->error(__('您没有权限查看'));
        }
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
             foreach ($list as $row){
                 if ($row->content){
                     $content=json_decode($row->content,true);
                     if ($content&&is_array($content)){
                         $row->content="";
                         if ($row->task_id){
                             $field=$this->getfield('task',false);
                         }else{
                             $field=$this->getfield('project',false);
                         }
                         foreach ($content as $key=>$v){
                             $v=is_array($v)?json_encode($v):$v;
                             if (preg_match("/(password|salt|token|price|expenses)/i", $key)) {//处理项目金额
                                 $v = "***";
                             }
                             if (isset($field[$key])){
                                 $row->content=$row->content?$row->content.",".$field[$key].":".$v:$field[$key].":".$v;
                             }else{
                                 $row->content=$row->content?$row->content.",".$key.":".($v):$key.":".($v);

                             }
                         }
                     }

                 }
             }

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //判断权限
        $auth = new \addons\workteam\library\Auth();

        if ($row->task_id&&!$auth->taskAuth($row->task_id, $this->auth)) {
            $this->error(__('您没有权限查看'));
        }
        if ($row->project_id&&!$auth->projectAuth($row->project_id, $this->auth)){
            $this->error(__('您没有权限查看'));
        }


		$show_keys = explode(',','id,username,title,content,create_time,service_client_text');
		$this->view->assign("show_keys", $show_keys);
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 添加
     * @internal
     */
    public function add()
    {
        $this->error();
    }

    /**
     * 编辑
     * @internal
     */
    public function edit($ids = null)
    {
        $this->error();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $adminList = $this->model->where('id', 'in', $ids)->select();
            if ($adminList) {
                $deleteIds = [];
                foreach ($adminList as $k => $v) {
                    $deleteIds[] = $v->id;
                }
                if ($deleteIds) {
                    $this->model->destroy($deleteIds);
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * @internal
     * @return \think\response\Json
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    /**
     * 获取参数字段
     * @param string $types types：project，task
     * @internal
     */
    public function getfield($types = "project", $return_ajax = true)
    {
        $cachename=md5($types);
        $fieldlist=cache($cachename);
        if (!$fieldlist){
            $prefix = \think\Config::get('database.prefix');
            $table = "{$prefix}workteam_{$types}";

            $dbname = \config('database.database');
            //从数据库中获取表字段信息
            $sql = "SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
            //加载主表的列
            $columnList = Db::query($sql, [$dbname, $table]);
            $fieldlist = [];
            foreach ($columnList as $index => $item) {
                $fieldlist[$item['COLUMN_NAME']] = $item['COLUMN_COMMENT'];
            }
        }

        if ($return_ajax) {
            $this->success("", null, $fieldlist);
        }
        return $fieldlist;
    }
}
